package com.rpa.server.servicerpaserver.crawler.operate;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rpa.secure.servicerpasecure.common.constant.ParameterConstant;
import com.rpa.secure.servicerpasecure.common.constant.UrlConstant;
import com.rpa.server.servicerpaserver.crawler.entity.Stu;
import com.rpa.server.servicerpaserver.crawler.service.StuService;
import com.rpa.server.servicerpaserver.util.CookieSerialize;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName StuOperate
 * @Description TODO
 * @Author 86152
 * @Date 2025/2/17 21:05
 * @Version 1.0
 **/

@Component
@Slf4j
public class StuOperate {
    @Autowired
    private CookieSerialize cookieSerialize;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StuService stuService;

    public void getStu(String accountId) {
        int year = DateUtil.year(DateUtil.date());
        int yearOffer = year - 1;
        String[] years = new String[]{yearOffer+"0",year+"0", year+"1",yearOffer + "1"};
        for (String y : years) {
            String academicYear;
            String semester;

            if (y.endsWith("0")) {
                academicYear = (Integer.parseInt(y.substring(0, 4)) - 1) + "-" + y.substring(0, 4);
                semester = "第一学期";
            } else {
                academicYear = y.substring(0, 4) + "-" + (Integer.parseInt(y.substring(0, 4)) + 1);
                semester = "第二学期";
            }
            String result = academicYear + "学年" + semester;
            MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
            requestParams.add("sel_xnxq", y);
            requestParams.add("hid_type", "xc");
            requestParams.add("initqry", "1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.set("Accept-Language",ParameterConstant.ACCEPT_LANGUAGE1);
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
            headers.set("Cookie", cookieSerialize.getCookieString(accountId+ "STU"));
            headers.set("Referer",ParameterConstant.HOST_TEST1);
            headers.set("Origin",ParameterConstant.ORIGIN_TEST1);
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(requestParams, headers);
            try {
                ResponseEntity<String> responseTrue = restTemplate.exchange(UrlConstant.YEAR_CLASS_LIST, HttpMethod.POST, entity, String.class);
                if (responseTrue.getStatusCode() == HttpStatus.OK) { // 检查 HTTP 状态码
                    String html = responseTrue.getBody();
                    if (html != null && !html.isEmpty()) {
                        List<Stu> stus = extractCourseInfo(html,accountId,result);
                        if (!stus.isEmpty()) {
                            LambdaUpdateWrapper<Stu> eq = new LambdaUpdateWrapper<Stu>()
                                    .eq(Stu::getAccountId, accountId);
                            stuService.remove(eq);
                            stuService.saveBatch(stus);
                        }
                    } else {
                        log.warn("获取的 HTML 内容为空");
                    }
                } else {
                    log.error("获取课程列表请求失败，HTTP 状态码: {}", responseTrue.getStatusCode());
                }
            }catch (Exception e){
                log.error("获取考试详细信息失败", e);
            }
        }
    }
    public List<Stu> extractCourseInfo(String html,String accountId,String year) {
        List<Stu> courseList = new ArrayList<>();
        if (html == null || html.isEmpty()) {
            return courseList; //  如果 HTML 为空，直接返回空列表
        }
        try {
            Document document = Jsoup.parse(html);
            Elements courseRows = document.select("table > tbody > tr.B, table > tbody > tr.H"); //  更精确的选择器

            for (Element row : courseRows) {
                Stu courseInfo = new Stu();
                courseInfo.setAccountId(accountId);
                courseInfo.setStuYear(year);
                Element courseNameCell = row.select("td:nth-child(1)").first();
                if (courseNameCell != null) {
                    courseInfo.setCourseName(courseNameCell.text().trim());
                }

                Element classNumberCell = row.select("td:nth-child(4)").first();
                if (classNumberCell != null) {
                    String classGroup = classNumberCell.attr("classgroup");
                    courseInfo.setClazzName(classGroup.replaceAll("#", ""));
                }

                Element linkCell = row.select("td.AT[onclick]").first();
                if (linkCell != null) {
                    String onclickValue = linkCell.attr("onclick");
                    String link = extractLinkFromOnclick(onclickValue)!= null ? extractLinkFromOnclick(onclickValue) : "";
                    courseInfo.setUrlLink(link);
                }
                courseList.add(courseInfo);
            }
        } catch (Exception e) {
            log.error("HTML 解析失败: {}", e.getMessage(), e); // 记录解析错误
        }

        return courseList;
    }
    private static String extractLinkFromOnclick(String onclickValue) {
        if (onclickValue == null || onclickValue.isEmpty()) {
            return null;
        }
        Matcher matcher = Pattern.compile("openWinX_new\\('(.*?)'").matcher(onclickValue);
        if (matcher.find()) {
            String link = matcher.group(1);
            if (link.startsWith("..")) {
                link = link.substring(2); // 去掉前面的 ../
            }
            return link;
        }
        return null;
    }

}
